package com.bawei.module_publish.openlive.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.module_publish.databinding.DialogLiveGoodsBinding
import com.bawei.module_publish.openlive.adapter.LiveGoodsAdapter
import com.bawei.module_publish.openlive.event.ExplainSuccessEvent
import com.bawei.module_publish.openlive.event.GoodsAddedEvent
import com.bawei.module_publish.openlive.event.GoodsCarEvent
import com.bawei.module_publish.openlive.intent.LiveIntent
import com.bawei.module_publish.openlive.model.entity.GoodRecord
import com.bawei.module_publish.openlive.model.entity.TopCarBody
import com.bawei.module_publish.openlive.state.LiveState
import com.bawei.module_publish.openlive.viewmodel.LiveViewModel
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

private const val TAG = "LiveGoodsDialog"
class LiveGoodsDialog constructor(private val roomId:String) : BottomSheetDialogFragment() {
    private var goodsList: List<GoodRecord> = listOf() // 实际使用时可传参或ViewModel获取
    private lateinit var liveViewModel: LiveViewModel
    private var _binding: DialogLiveGoodsBinding? = null
    private val binding get() = _binding!!
    private var goodList = mutableListOf<GoodRecord>()
    private val LiveGoodsAdapter: LiveGoodsAdapter by lazy {
        LiveGoodsAdapter(goodList,
            onExplainClick = {
                ExplainDialog(it.id.toString(),goodList) { goodsId ->

                }.show(parentFragmentManager, "ExplainDialog")
            },
            onItemClick = {
                val topCarBody = TopCarBody(it.id.toString(), "285417033236483")
                lifecycleScope.launch {
                    liveViewModel.intents.send(LiveIntent.ExplainGoods(topCarBody))
                }
                ToastUtils.showShort( "你已知晓讲解回放功能")
                EventBus.getDefault().post(ExplainSuccessEvent(it))
            }
        )
    }
    override fun onStart() {
        super.onStart()
        dialog?.let {
            val bottomSheet = it.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            bottomSheet?.layoutParams?.height = (resources.displayMetrics.heightPixels * 0.85).toInt()
            bottomSheet?.requestLayout()
        }
        EventBus.getDefault().register(this)
    }
    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGoodsCared(event: GoodsCarEvent) {
        // 收到事件后刷新数据
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.LiveRoomGoods(roomId))
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding= DialogLiveGoodsBinding.inflate(inflater, container, false)
        liveViewModel = ViewModelProvider(this)[LiveViewModel::class.java]
        // 初始全部隐藏，等待数据
        binding.layoutStatsTabs.visibility = View.GONE
        binding.rvGoods.visibility = View.GONE
        binding.emptyLayout.visibility = View.GONE
        binding.rvGoods.adapter = LiveGoodsAdapter
        binding.rvGoods.layoutManager = LinearLayoutManager(BaseApplication.instance)
        return binding.root
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.LiveRoomGoods(roomId))
        }
        binding.btnAddGoods.setOnClickListener {
            AddGoodsDialog { selectedGoods ->
                // 更新商品列表逻辑
                goodsList = selectedGoods
                updateGoodsUI()
            }.show(parentFragmentManager, "AddGoodsDialog")
        }
        binding.ivSetting.setOnClickListener {
            AddGoodsDialog { selectedGoods ->
                // 更新商品列表逻辑
                goodsList = selectedGoods
                updateGoodsUI()
            }.show(parentFragmentManager, "AddGoodsDialog")
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._getGoodsFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                            goodsList = listOf()
                            updateGoodsUI()
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败${it.msg}")
                            goodsList = listOf()
                            updateGoodsUI()
                        }
                        is LiveState.GetGoodsListSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            goodsList = it.msg.records
                            LiveGoodsAdapter.setData(it.msg.records)
                            updateGoodsUI()
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                liveViewModel._explainGoodsFlow.collect {
                    when(it){
                        is LiveState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is LiveState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is LiveState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败${it.msg}")
                        }
                        is LiveState.ExplainGoodsSuccess -> {
                            Log.d(TAG, "handleState: ${it.msg}")
                            dismiss()
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据商品数据联动UI
     */
    private fun updateGoodsUI() {
        if (goodsList.isNullOrEmpty()) {
            binding.layoutStatsTabs.visibility = View.GONE
            binding.rvGoods.visibility = View.GONE
            binding.emptyLayout.visibility = View.VISIBLE
        } else {
            binding.layoutStatsTabs.visibility = View.VISIBLE
            binding.rvGoods.visibility = View.VISIBLE
            binding.emptyLayout.visibility = View.GONE
        }
        // 更新标题数量
        binding.tvTitle.text = "直播商品 (${goodsList.size})"
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch {
            liveViewModel.intents.send(LiveIntent.LiveRoomGoods(roomId))
        }
    }
}